<?php

namespace Warehouse\Controller;

use Home\Controller\CommonController;
use Inbound\Service\PublicPlugService;
use Inbound\Service\PublicInfoService;
use Warehouse\Service\BaseInfoService;
const SKU_PICTURE = 'http://skuimg.kokoerp.com/api/?c=api_pictureurl_urlservers&a=get_pictureurl';
class StockInController extends CommonController

{
    //模型层对象
    public $StockInmodel = NULL;

    //条件
    public $condition = array();


    //标志符
    public $flag;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        if(array_filter($_POST)){
            $this->condition = array_filter($_POST);
        }elseif(array_filter($_GET)){
            $this->condition = array_filter($_GET);
        }
        $this->StockInmodel        = D('Warehouse/StockIn','Model');
        $this->StockService        = D('Warehouse/StockIn','Service');
        $this->Storage             = D('Warehouse/Storage','Model');
        $this->export_tax_rebate   = BaseInfoService::export_tax_rebate();
        $this->enterprise_dominant = BaseInfoService::enterprise_dominant();
        $this->transfer_hopper_id  = BaseInfoService::transfer_hopper_id();
        $this->transfer_type       = BaseInfoService::transfer_type();
        $this->stock_in_type       = BaseInfoService::stock_in_type();
        $this->site_id             = PublicInfoService::get_site_array();
    }

    /**
     * 描述：特殊入库界面
     */
    public function  index()
    {
        $stock_in_type = $this->stock_in_type;
        unset($stock_in_type[10]);    //正常采购入库
        unset($stock_in_type[130]);   //移位入库
        unset($stock_in_type[150]);   //站点调拨
        $this->assign('export_tax_rebate',$this->export_tax_rebate);
        $this->assign('enterprise_dominant',$this->enterprise_dominant);
        $this->assign('stock_in_type',$stock_in_type);
        $this->assign('transfer_hopper_id',$this->transfer_hopper_id);
        $this->assign('transfer_type',$this->transfer_type);
        $this->assign('site_id',$this->site_id);
        $this->display();
    }

    /**
     * 描述：入库明细界面
     */
    public function  StockIn_Detail()
    {
        if($_GET){
            $data = $this->StockInmodel->get_warehouseorders_model_details($this->condition,$flag = TRUE);
        }
       /* $arr2 = array_column($data, 'sku');
        $q = $arr2[1];
        var_dump($q);exit;*/
        $this->assign('page',$this->StockInmodel->page);
        $this->assign('count',$this->StockInmodel->count);
        $this->assign('data',$data);
        $this->assign('export_tax_rebate',$this->export_tax_rebate);
        $this->assign('enterprise_dominant',$this->enterprise_dominant);
        $this->assign('stock_in_type',$this->stock_in_type);
        $this->assign('transfer_hopper_id',$this->transfer_hopper_id);
        $this->assign('transfer_type',$this->transfer_type);
        $this->display();
    }

    /**
     * 描述：质检入库界面
     */
    public function  Qc_StockIn()
    {
        if((isset($this->condition['id'])&&$this->condition['id'])||(isset($this->condition['sku'])&&$this->condition['sku'])){
            $data             = $this->StockInmodel->get_check_quality_details($this->condition,TRUE);
            $export_tax_rebate= array_search($data[0]['export_tax_rebate'],$this->export_tax_rebate);
            $storage_position = BaseInfoService::GetSkuStorage(array('sku' => $data[0]['sku'],'export_tax_rebate'=>$export_tax_rebate));
            $this->assign('storage_position',$storage_position);
            $this->assign('data',$data);
        }
        $this->display();
    }

    /**
     * 描述：正常质检入库
     */
    public function  batch_create()
    {
        $data   = isset($this->condition['page_data'])?$this->condition['page_data']:array();
        $_array = array();
        if($data){
            foreach($data AS $k => $v){
                $_array[$k]['warehouse_date']          = date("Y-m-d H:i:s");
                $_array[$k]['op_time']                 = date("Y-m-d H:i:s");
                $_array[$k]['check_quality_detail_id'] = $v['check_quality_detail_id']?$v['check_quality_detail_id']:'';
                $_array[$k]['batch_code']              = $v['batch_code']?$v['batch_code']:'';
                $_array[$k]['purchaseorders_id']       = $v['purchaseorders_id']?$v['purchaseorders_id']:'';
                $_array[$k]['warehouse_quantity']      = $v['quantity']?$v['quantity']:'';
                $_array[$k]['available_quantity']      = $v['quantity']?$v['quantity']:'';
                $_array[$k]['stockin_num']             = $v['stockin_num']?$v['stockin_num']:'';
                $_array[$k]['storage_position']        = $v['storage_position']?$v['storage_position']:'';
                $_array[$k]['store']                   = $v['store']?$v['store']:'';
                $_array[$k]['sku']                     = $v['sku']?$v['sku']:'';
                $_array[$k]['sku_name']                = $v['sku_name']?$v['sku_name']:'';
                //10正常采购入库20订单销售退回（退件入库）30盘赢40供应商礼物50样品归还
                $_array[$k]['type'] = $v['type']?$v['type']:'';;
                $_array[$k]['warehouse_man']       = $_SESSION['current_account']['id'];
                $_array[$k]['transfer_hopper_id']  = array_search($v['transfer_hopper_id'],$this->transfer_hopper_id);
                $_array[$k]['transfer_type']       = array_search($v['transfer_type'],$this->transfer_type);
                $_array[$k]['export_tax_rebate']   = array_search($v['export_tax_rebate'],$this->export_tax_rebate);
                $_array[$k]['site_id']             = array_search($v['site_id'],$this->site_id);
                $_array[$k]['enterprise_dominant'] = array_search($v['enterprise_dominant'],$this->enterprise_dominant);
                $_array[$k]['supplier_id']         = BaseInfoService::supplier_id($v['supplier_id']);
                //获取采购单明细中sku的单价和运费
                $money_detail        = $this->StockService->purchaseorder_details(array(
                    'purchaseorder_id' => $_array[$k]['purchaseorders_id'],
                    'sku'              => $_array[$k]['sku']
                ));
                $_array[$k]          = array_merge($_array[$k],$money_detail);
                $_array[$k]['money'] = $_array[$k]['warehouse_quantity']*$_array[$k]['single_price'];
                $_array[$k]['cost']  = $_array[$k]['money']+($_array[$k]['warehouse_quantity']*$_array[$k]['transportation_expense']);
            }

            $result = $this->StockInmodel->batch_create($_array);
            echo json_encode(array(
                'status' => $this->StockInmodel->flag,
                'data'   => $result
            ));
            exit;
        }
    }

    /**
     * 描述：特殊入库
     */
    public function  Special_StockIn()
    {
        if($this->condition){
            foreach($this->condition AS $k => $v){
                $this->condition[$k]['warehouse_date']    = date("Y-m-d H:i:s");
                $this->condition[$k]['supplier_id']       = BaseInfoService::supplier_id($v['supplier_id']);
                $this->condition[$k]['warehouse_man']     = $_SESSION['current_account']['id'];
                $this->condition[$k]['export_tax_rebate'] = $v['export_tax_rebate']?$v['export_tax_rebate']:'0';
            }
            $data = $this->StockInmodel->batch_create($this->condition,TRUE);
        }
        echo json_encode(array(
            'status' => $this->StockInmodel->flag,
            'data'   => $data
        ));
        exit;
    }

    /**
     * 描述：反仓入库接口
     */
    public function  Back_StockIn($_array)
    {
        $data = array();
        if($_array){
            foreach($_array AS $k => $v){
                $warehouse_id                        = M('warehouse_deliveryorders','wms_','fbawarehouse')
                    ->where(array('deliveryorders_id' => $v['deliveryorders_id']))
                    ->getfield('warehouseorders_id');
                $where['id']                         = $warehouse_id;
                $where['sku']                        = strtoupper(trim($v['sku']));
                $StockIn                             = $this->StockInmodel->warehouseorders->where($where)
                    ->select();
                $data[$k]['type']                    = $v['type'];
                $data[$k]['storage_position']        = $v['storage_position'];
                $data[$k]['warehouse_quantity']      = $v['warehouse_quantity'];
                $data[$k]['available_quantity']      = $v['warehouse_quantity'];
                $data[$k]['site_id']                 = $v['site_id']?$v['site_id']:0;
                $data[$k]['warehouse_date']          = date("Y-m-d H:i:s");
                $data[$k]['op_time']                 = date("Y-m-d H:i:s");
                $data[$k]['sku']                     = strtoupper(trim($StockIn[0]['sku']));
                $data[$k]['sku_name']                = $StockIn[0]['sku_name'];
                $data[$k]['batch_code']              = $StockIn[0]['batch_code'];
                $data[$k]['check_quality_detail_id'] = $StockIn[0]['check_quality_detail_id'];
                $data[$k]['supplier_id']             = $StockIn[0]['supplier_id'];
                $data[$k]['store']                   = $StockIn[0]['store'];
                $data[$k]['export_tax_rebate']       = $StockIn[0]['export_tax_rebate'];
                $data[$k]['enterprise_dominant']     = $StockIn[0]['enterprise_dominant'];
                $data[$k]['transfer_hopper_id']      = $StockIn[0]['transfer_hopper_id'];
                $data[$k]['transfer_type']           = $StockIn[0]['transfer_type'];
                $data[$k]['single_price']            = $StockIn[0]['single_price'];
                $data[$k]['cost']                    = $StockIn[0]['cost'];
                $data[$k]['transportation_expense']  = $StockIn[0]['transportation_expense'];
                $data[$k]['money']                   = $StockIn[0]['money'];
                $data[$k]['tax_price']               = $StockIn[0]['tax_price'];
                $data[$k]['pre_warehouseorder_id']   = $StockIn[0]['id'];
            }

            $result = $this->StockInmodel->batch_create($data,TRUE);
        }
        return $result?$result:array();
    }


    /**
     * 描述：批量导入特殊入库 
     */
    public function  Special_batch_create()
    {
        $result = PublicPlugService::parse_excel();
        if(!PublicPlugService::$flag){    //选择了上传文件,状态返回false
            $data = array();
            $msg  = array();
            foreach($result AS $k => $v){
                if($result[1]['A']!=='入库类型'||$result[1]['B']!=='SKU'||$result[1]['C']!=='数量'||$result[1]['D']!=='储位'||
                    $result[1]['E']!=='是否出口退税'||$result[1]['F']!=='公司主体'||$result[1]['G']!=='站点'||$result[1]['H']!=='备注'){
                    $flag[] = '上传的表格的表头有问题';
                }
                if($k>1){
                    if(array_search(trim($v['A']),$this->stock_in_type)==''){
                        $flag[] = '第'.$k.'条数据的特殊入库类型不存在！';
                    }
                    if(trim($v['B'])==''){
                        $flag[] = '第'.$k.'条数据的SKU不能为空！';
                    }
                    if(trim($v['C'])==''||trim($v['C'])==0){
                        $flag[] = '第'.$k.'条数据的数量必须填写！';
                    }
                    if(trim($v['D'])==''||$this->Storage->get_storage_by_where(array('storage_position' => trim($v['D'])))==''){
                        $flag[] = '第'.$k.'条数据的储位不存在！';
                    }
                    if(array_search(trim($v['E']),$this->export_tax_rebate)!==0&&array_search(trim($v['E']),$this->export_tax_rebate)!==1){
                        $flag[] = '第'.$k.'条数据的是否出口退税类型不存在！';
                    }
                    if(array_search(trim($v['F']),$this->enterprise_dominant)==''){
                        $flag[] = '第'.$k.'条数据的公司主体不存在！';
                    }
                    if(array_search(trim($v['G']),$this->site_id)==''){
                        $flag[] = '第'.$k.'条数据的站点不可用或是不存在！';
                    }
                    if(self::Judge_is_skucname_byexport_tax_rebate(array('sku'=>trim($v['B']),'storage_position'=>trim($v['D']),'export_tax_rebate'=> array_search(trim($v['E']),$this->export_tax_rebate)))==false){
                        $flag[] = '第'.$k.'条数据的sku和要绑定的储位的是否出口退税性质不一致！';
                    }
                    if(empty($flag)){
                        $data[] = array(
                            'warehouse_date'      => date("Y-m-d H:i:s"),
                            'op_time'             => date("Y-m-d H:i:s"),
                            'warehouse_man'       => $_SESSION['current_account']['id'],
                            'type'                => array_search(trim($v['A']),$this->stock_in_type),
                            'sku'                 => strtoupper(trim($v['B'])),
                            'warehouse_quantity'  => trim($v['C']),
                            'available_quantity'  => trim($v['C']),
                            'storage_position'    => trim($v['D']),
                            'export_tax_rebate'   => array_search(trim($v['E']),$this->export_tax_rebate),
                            'enterprise_dominant' => array_search(trim($v['F']),$this->enterprise_dominant),
                            'site_id'             => array_search(trim($v['G']),$this->site_id),
                            'remark'              => trim($v['H'])
                        );
                        $storage_sku=$this->Storage->get_storage_sku_by_where(array('storage_position' => trim($v['D']), 'sku'=> trim($v['B'])),$field = '*');
                        if(empty($storage_sku)){
                            $export_tax_rebate = $this->Storage->get_storage_by_where(array('storage_position' => trim($v['D'])));
                            $Storage[]         = array(
                                'storage_position'  => trim($v['D']),
                                'sku'               => trim($v['B']),
                                'export_tax_rebate' => $export_tax_rebate['export_tax_rebate']?$export_tax_rebate['export_tax_rebate']:0,
                            );
                        }
                    }
                    $flag?$msg[] = $flag:'';
                    unset($flag);
                }
            }
            $Storage?$this->Storage->add_storage_sku($Storage):FALSE;
            $msg?'':$this->StockInmodel->batch_create($data);
        }else{
            $msg[] = '上传的表格有问题';
        }
        echo json_encode(array('data' => $msg?$msg:'全部上传成功'));
        exit;
    }

    /**
     *下载上传特殊入库单的模板
     */
    public function down_template()
    {
        set_time_limit(0);
        vendor('PHPExcel.PHPExcel.IOFactory');
        $this->objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new \PHPExcel();

        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','入库类型');
        $objActSheet->setCellValue('B1','SKU');
        $objActSheet->setCellValue('C1','数量');
        $objActSheet->setCellValue('D1','储位');
        $objActSheet->setCellValue('E1','是否出口退税');
        $objActSheet->setCellValue('F1','公司主体');
        $objActSheet->setCellValue('G1','站点');
        $objActSheet->setCellValue('H1','备注');
        $objActSheet->setCellValue('A2','盘赢');
        $objActSheet->setCellValue('B2','A404');
        $objActSheet->setCellValue('C2','20');
        $objActSheet->setCellValue('D2','MH1-01');
        $objActSheet->setCellValue('E2','出口退税');
        $objActSheet->setCellValue('F2','有棵树电子商务有限公司');
        $objActSheet->setCellValue('G2','EB');
        $objActSheet->setCellValue('H2','111备注');

        $objPHPExcel->getActiveSheet()
            ->setTitle('delivery_special');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("m-d");
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename="'.$day.'特殊入库单.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 描述：判断sku与储位的绑定关系
     */
    public function  Judge_is_sku_cname()
    {
        if($this->condition){
            if(trim($this->condition['sku'])){
                $where['check_quality_detail_id'] = $this->condition['check_quality_detail_id'];
                $StockIn                          = $this->StockInmodel->get_warehouseorders_model_details($where);
                $StockIn?$this->flag = FALSE:$this->flag = TRUE;
                foreach($this->condition['storage_position'] AS $k => $v){
                    $data = BaseInfoService::Judge_is_sku_cname(array(
                        'sku'              => $this->condition['sku'],
                        'storage_position' => $this->condition['storage_position'][$k]
                    ),TRUE);
                    $this->flag?($data?$this->flag = TRUE:$this->flag = FALSE):$this->flag = FALSE;
                }
            }
        }
        echo json_encode(array('flag' => $this->flag));
        exit;
    }

    /**
     * 描述：根据sku获取储位
     */
    public function  GetSkuStorage()
    {
        if($this->condition){
            if(trim($this->condition['sku'])){
                $data = BaseInfoService::GetSkuStorage($this->condition,TRUE);
            }
        }
        echo json_encode(array('flag' => $data));
        exit;
    }

    /**
     * 描述：判断sku与储位的绑定关系
     */
    public function  Judge_is_skucname()
    {
        $condition=array(
            'sku'=>$_POST['sku'],
            'storage_position'=>$_POST['storage_position'],
            'export_tax_rebate'=>$_POST['export_tax_rebate']
        );
        if($condition){
            if(trim($condition['sku'])&&trim($condition['storage_position'])){
                $data = BaseInfoService::Judge_is_sku_cname($condition,TRUE);
            }
        }
        if(empty($data)){
            $this->flag = FALSE;
        }else{
            $this->flag = TRUE;
        }

        echo json_encode(array('flag' => $this->flag));
        exit;
    }

    /**
     * 描述：判断sku与储位的绑定关系
     */
    public function  Judge_is_skucname_byexport_tax_rebate($data)
    {
        $condition=array(
            'sku'=>$data['sku'],
            'storage_position'=>$data['storage_position'],
            'export_tax_rebate'=>$data['export_tax_rebate']
        );
        if($condition){
            if(trim($condition['sku'])&&trim($condition['storage_position'])){
                $data = BaseInfoService::Judge_is_sku_cname($condition,TRUE);
            }
        }
        if(empty($data)){
            $this->flag = FALSE;
        }else{
            $this->flag = TRUE;
        }

        return $this->flag;
    }
    /**
     * 描述：获取供应商的信息
     */
    public function  get_supplier_info()
    {
        if($this->condition['sku']){
            $data = $this->StockService->get_supplier_by_sku($this->condition,TRUE);
        }
        echo json_encode(array('data' => $data));
        exit;
    }
    /*获取单个SKU图片*/
    public function getSkuImage($sku) {

        $data = array(
            "sku"        => trim($sku),
            "gallery_id" => '1',
            "type"       => "ALL",
            "all_type"   => "false",
            "url_type"   => 'http'
        );
        $skuData = $this->getSkuSystemImgData($data,SKU_PICTURE);

        $data = json_decode($skuData,true);
        $re = current(current(current(current($data))));
        if($re){
            return $re;
        }else{
            return null;
        }
    }
    /**
     * 描述 ： 通过CURL获取SKU基础资料数据
     */
    public function getSkuSystemImgData($postData, $url) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * 描述：入库明细报表下载
     */
    public function Down_StockIn_Detail()
    {
        set_time_limit(0);

        ini_set('memory_limit','2048M');

        if(!empty($_GET)){
            $sql = $this->StockInmodel->get_warehouseorders_model_details_sql($_GET,$flag = TRUE);

            foreach ($sql as $c=>&$row){
                $row['site_id'] =$this->site_id[$row['site_id']];
                $row['type'] =$this->stock_in_type[$row['type']];
                $row['export_tax_rebate'] =$this->export_tax_rebate[$row['export_tax_rebate']];
                $row['enterprise_dominant'] =$this->enterprise_dominant[$row['enterprise_dominant']];
                $row['transfer_hopper_id'] =$this->transfer_hopper_id[$row['transfer_hopper_id']];
                $row['transfer_type'] =$this->transfer_type[$row['transfer_type']];
                $row['supplier_id'] =BaseInfoService::supplier_name($row['supplier_id']);
                $row['sku_name'] =str_replace(array("\r\n", "\r", "\n", '<br/>', '<br>'), '', $row['sku_name']);
//                $sql[$c]['url'] = $this->getSkuImage($row['sku']);
                $row['warehouse_man']=BaseInfoService::get_user_name($row['warehouse_man']);
            }
            self::exportTrueImage($sql);
        }
    }

    /**
     * 导出数据(含图片）到Excel
     */
    public static function exportTrueImage($ranking) {
        vendor('PHPExcel.PHPExcel');
        vendor('PHPExcel.PHPExcel.IOFactory');
        define('EXCEL_IMAGE_PATH',dirname(dirname(dirname(dirname(__FILE__)))).'/Cache/Runtime/Admin/Cache');
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        $objPHPExcel = new \PHPExcel();                                                                                 // Create new PHPExcel object
        $objPHPExcel->getProperties()->setCreator("ctos")                                                               // Set properties
        ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        //设置列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        //设置水平居中显示
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '入库单号')
            ->setCellValue('C1', '站点')
            ->setCellValue('D1', '入库类型')
            ->setCellValue('E1', '采购单')
            ->setCellValue('F1', '批次号')
            ->setCellValue('G1', '储位号')
            ->setCellValue('H1', '性质')
            ->setCellValue('I1', '主体')
            ->setCellValue('J1', '中转仓')
            ->setCellValue('K1', '运输方式')
            ->setCellValue('L1', '入库日期')
            ->setCellValue('M1', 'SKU')
//            ->setCellValue('N1', '缩略图')
            ->setCellValue('N1', '中文名称')
            ->setCellValue('O1', '供应商')
            ->setCellValue('P1', '单价')
            ->setCellValue('Q1', '入库数量')
            ->setCellValue('R1', '可用数量')
            ->setCellValue('S1', '金额')
            ->setCellValue('T1', '成本')
            ->setCellValue('U1', '运费')
            ->setCellValue('V1', '备注')
            ->setCellValue('W1', '入库人');
        $objPHPExcel->setActiveSheetIndex(0)->getRowDimension(1)->setRowHeight(15);
        $a = 1;
        foreach ($ranking as $k) {
            $a++;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $a, $a-1)
                ->setCellValue('B' . $a, $k['id'])
                ->setCellValue('C' . $a, $k['site_id'])
                ->setCellValue('D' . $a, $k['type'])
                ->setCellValue('E' . $a, $k['purchaseorders_id'])
                ->setCellValue('F' . $a, $k['batch_code'])
                ->setCellValue('G' . $a, $k['storage_position'])
                ->setCellValue('H' . $a, $k['export_tax_rebate'])
                ->setCellValue('I' . $a, $k['enterprise_dominant'])
                ->setCellValue('J' . $a, $k['transfer_hopper_id'])
                ->setCellValue('K' . $a, $k['transfer_type'])
                ->setCellValue('L' . $a, $k['warehouse_date'])
                ->setCellValue('M' . $a, $k['sku'])
//                ->setCellValue('N' . $a, '无')
                ->setCellValue('N' . $a, $k['sku_name'])
                ->setCellValue('O' . $a, $k['supplier_id'])
                ->setCellValue('P' . $a, $k['single_price'])
                ->setCellValue('Q' . $a, $k['warehouse_quantity'])
                ->setCellValue('R' . $a, $k['available_quantity'])
                ->setCellValue('S' . $a, $k['money'])
                ->setCellValue('T' . $a, $k['cost'])
                ->setCellValue('U' . $a, $k['transportation_expense'])
                ->setCellValue('V' . $a, $k['remark'])
                ->setCellValue('W' . $a, $k['warehouse_man']);

            /*********************************图片处理*star1***************************/
              /*  if(!preg_match('/^(http|https):\/\/(.*?)\.(jpg|png|jpeg)$/i',$k['url'])){
                    $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('N' . $a, '此sku在基础资料图片库无缩略图');
                    continue;
                }
                $url = parse_url($k['url']);
                $url['path'] = str_replace('/', '_', $url['path']);
                $file_exitis = file_exists(EXCEL_IMAGE_PATH. $url['path']);
                if (!$file_exitis) {
                    $cnt=0;
                    $img_data=false;
                    while($cnt < 3 && ($img_data=@file_get_contents($k['url']))===FALSE) $cnt++;
                    if($img_data!==false){
                        file_put_contents( EXCEL_IMAGE_PATH.$url['path'], $img_data);
                    }
                }
                //自动适应
                $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
                $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
                //设置换行
                $objPHPExcel->getActiveSheet()->getStyle("A$a")->getAlignment()->setWrapText(true);
                $objPHPExcel->getActiveSheet()->getStyle("N$a")->getAlignment()->setWrapText(true);
                //设置垂直居中显示
                $objPHPExcel->getActiveSheet()->getStyle("A$a")->getAlignment()
                    ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle("N$a")->getAlignment()
                    ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle("N$a")->getAlignment()
                    ->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                //设置行高
                $objPHPExcel->setActiveSheetIndex(0)->getRowDimension($a)->setRowHeight(100);
                if($file_exitis ){//只要图片原来存在或者获取下载到了图片就把图片放在里面
                    $objDrawing = new \PHPExcel_Worksheet_Drawing();
                    $objDrawing->setName('产品缩略图');
                    $objDrawing->setDescription('产品缩略图');
                    $objDrawing->setPath( EXCEL_IMAGE_PATH . $url['path']);
                    $objDrawing->setCoordinates("N".$a);
                    $objDrawing->setWidth(120);
                    $objDrawing->setOffsetX(8);
                    $objDrawing->setOffsetY(8);
                    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                }*/
            /*********************************图片处理*end1***************************/
        }

        $objPHPExcel->getActiveSheet()->setTitle('入库明细报表');
        $objPHPExcel->setActiveSheetIndex(0);
        // excel头参数
        //ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="入库明细报表(' . date('Y-m-d') . ').xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;


    }

    /**
     * 储位列表
     */
    public function storage_lists()
    {
        $result = $this->Storage->get_storage_data($_GET);

        $this->assign('result',$result);
        $this->assign('page',$this->Storage->page);
        $this->assign('count',$this->Storage->count);
        $this->display('Storage/index');
    }


    /**
     * 添加储位
     */
    public function add_storage()
    {
        if(IS_POST){
            $post_data = I('post.');

            //验证储位编码唯一性
            $storage = $this->Storage->get_storage_by_where(array('storage_position' => trim($post_data['storage_position'])));
            if($storage){
                return $this->errorReturn('储位编码【'.$post_data['storage_position'].'】已存在！请重新输入！');
            }

            $post_data['adderid']     = $_SESSION['current_account']['id'];
            $post_data['create_time'] = $post_data['update_time'] = date('Y-m-d H:i:s');

            $result = $this->Storage->add_storage($post_data);
            if(!$result){
                return $this->errorReturn('添加储位失败！请重试！');
            }

            return $this->successReturn('添加储位成功！');
        }else{
            $this->display('Storage/add');
        }
    }

    /**
     * 编辑储位
     */
    public function edit_storage()
    {
        if(IS_POST){
            $post_data = I('post.');

            //验证储位编码唯一性
            if($post_data['storage_position']!=$post_data['old_storage_position']){
                $storage = $this->Storage->get_storage_by_where(array('storage_position' => trim($post_data['storage_position'])));
                if($storage){
                    return $this->errorReturn('储位编码【'.$post_data['storage_position'].'】已存在！请重新输入！');
                }
            }

            $post_data['update_time'] = date('Y-m-d H:i:s');
            unset($post_data['old_storage_position']);
            $result = $this->Storage->save_storage($post_data,array('id' => $post_data['id']));
            if(!$result){
                return $this->errorReturn('保存储位失败！请重试！');
            }

            //如果该储位已经绑定sku，则更新sku和储位关联表中的出口退税和主体字段
            $storage_sku = $this->Storage->get_storage_sku_by_where(array('storage_position' => $post_data['storage_position']));
            if($storage_sku){
                $this->Storage->save_storage_sku(
                    array(
                        'enterprise_dominant' => $post_data['enterprise_dominant'],
                        'export_tax_rebate'   => $post_data['export_tax_rebate']
                    ),
                    array('storage_position' => $post_data['storage_position'])
                );
            }

            return $this->successReturn('保存储位成功！');
        }else{
            $data = $this->Storage->get_storage_by_where(array('id' => I('get.id')));

            $this->assign('data',$data);
            $this->display('Storage/edit');
        }
    }


    /**
     * 更新储位状态
     */
    public function set_storage_status()
    {
        if(I('post.status')==0){
            //判断储位是否还有可使用量，如果可使用量大于0，则不能解绑
            $where              = array('storage_position' => I('post.storage_position'));
            $available_quantity = $this->Storage->get_storage_availiable($where);
            if($available_quantity>0){
                return $this->errorReturn('当前储位还有入库单可使用量，不能禁用！');
            }
        }

        $result = $this->Storage->save_storage(array('status' => I('post.status')),array('id' => I('post.id')));
        if(!$result){
            return $this->errorReturn('操作失败！请重试！');
        }

        return $this->successReturn('操作成功！');
    }


    /**
     * 储位绑定sku
     */
    public function storage_bind_sku()
    {
        $storage_position  = I('post.storage_position');
        $export_tax_rebate = I('post.export_tax_rebate');
        $sku_old           = I('post.sku_old')?array_unique(explode(',',str_replace("，",",",I('post.sku_old')))):'';
        $sku               = I('post.sku')?array_unique(explode(',',str_replace("，",",",I('post.sku')))):'';

        //储位信息
        $storage = $this->Storage->get_storage_by_where(array('storage_position' => $storage_position));

        if($sku){
            //判断sku库是否存在
            $skudata = $this->Storage->get_sku_info(array(
                'sku' => array(
                    'IN',
                    $sku
                )
            ),'sku');
            $skudata = i_array_column($skudata,'sku');

            if(count($skudata)==0||count($skudata)<count($sku)){
                $diff_sku = implode(',',array_diff($sku,$skudata));
                return $this->errorReturn('sku【'.$diff_sku.'】不存在！');
            }

            //判断储位下的sku是否还有可使用量，如果可使用量大于0，则不能解绑
            $remove_sku = array_diff($sku_old,array_intersect($sku_old,$sku));  //移除的sku
            if($remove_sku){
                foreach($remove_sku as $k => $v){
                    $where              = array(
                        'storage_position' => $storage_position,
                        array('sku' => $v)
                    );
                    $available_quantity = $this->Storage->get_storage_availiable($where);
                    if($available_quantity>0){
                        return $this->errorReturn('当前储位下的sku【'.$v.'】还有入库单可使用量，不能解绑！');
                    }
                }
            }

            //先删除原来绑定的数据，再重新绑定
            $this->Storage->del_storage_sku(array('storage_position' => $storage_position));

            foreach($sku as $key => $value){
                $bind_data[$key]['storage_position']    = $storage_position;
                $bind_data[$key]['sku']                 = $value;
                $bind_data[$key]['enterprise_dominant'] = $storage['enterprise_dominant'];
                $bind_data[$key]['export_tax_rebate']   = $export_tax_rebate;
            }
            $result = $this->Storage->add_storage_sku($bind_data);
        }else{
            //判断储位是否还有可使用量，如果可使用量大于0，则不能解绑
            $where              = array('storage_position' => $storage_position);
            $available_quantity = $this->Storage->get_storage_availiable($where);
            if($available_quantity>0){
                return $this->errorReturn('当前储位还有入库单可使用量，不能解绑！');
            }

            $result = $this->Storage->del_storage_sku(array('storage_position' => $storage_position));
        }

        if(!$result){
            return $this->errorReturn('操作失败！请重试！');
        }

        return $this->successReturn('操作成功！');
    }


    /**
     * 期初库存导入
     */
    public function warehouse_import()
    {
        if(IS_POST){
            //解析excel内容
            $import_data = PublicPlugService::parse_excel();
            if(PublicPlugService::$flag){
                return $this->errorReturn('请选择上传文件！');
            }

            if(count($import_data)<2){
                return $this->errorReturn('文件内容为空！');
            }

            //检查导入的数据合法性
            $check_data = $this->StockInmodel->check_warehouse_import_data($import_data);
            if(!$check_data['status']){
                return $this->errorReturn($check_data['message']);
            }

            //写入入库单表
            $result = $this->StockInmodel->add_warehouseorders($import_data);
            if(!$result['flag']){
                return $this->errorReturn($result['message']);
            }

            return $this->successReturn($result['message']);
        }else{
            $this->display();
        }
    }


    /**
     * 导出期初库存导入模板
     */
    public function download()
    {
        PublicPlugService::download_templet();
    }

    /**
     * 根据SKU获取相应主图URL
     */
    public static function skuFindUrl($sku){
        $sql = "SELECT image_url FROM image WHERE sku='".$sku."' AND file_name LIKE '%ALL%'";
        $image = DB::query(Database::SELECT,$sql)->execute('skusystem')->current();
        if($image){
            $file_name=$image['image_url'];
        }else{
            $file_name='不存在SKU:'.$sku.'主图,请通知资料组补全';
        }
        return $file_name;
    }
}